/* eslint-disable vue/no-unused-vars */
<template>
  <div>
    <bread>
      <span slot="second">商品管理</span>
      <span slot="third">参数列表</span>
    </bread>

    <el-card>
      <el-alert title="注意！只允许为第三级分类设置相关参数" type="warning" :closable="false"></el-alert>
      <!-- 选择商品分类 -->
      <el-row>
        <el-col class="cat_opt">
          <span>选择商品分类：</span>
          <el-cascader
            v-model="goodsParamss"
            :options="cateList"
            :props="goodsParamssProps"
            @change="paramsChange"
            clearable
          ></el-cascader>
        </el-col>
      </el-row>
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            size="mini"
            :disabled="goodsParamss.length === 3 ? false : true"
            @click="addParamsdialogVisible=true"
          >添加参数</el-button>
          <el-table :data="paramsmanyList" border stripe>
            <el-table-column type="expand">
              <template v-slot="scope">
                <!-- 循环的文本框 -->
                <el-tag
                  v-for="(item,index) in scope.row.attr_vals"
                  :key="index"
                  closable
                  @close="removevals(index,scope.row)"
                >{{item}}</el-tag>
                <!-- 添加按钮 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                  style="width:200px"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column label="#" type="index"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template v-slot="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  @click="editDialog(scope.row.attr_id)"
                >编辑</el-button>
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  @click="removeParams(scope.row.attr_id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button
            type="primary"
            size="mini"
            :disabled="goodsParamss.length === 3 ? false : true"
            @click="addParamsdialogVisible=true"
          >添加属性</el-button>
          <el-table :data="paramsonlyList" border stripe>
            <el-table-column type="expand">
              <template v-slot="scope">
                <!-- 循环的文本框 -->
                <el-tag
                  v-for="(item,index) in scope.row.attr_vals"
                  :key="index"
                  closable
                  @close="removevals(index,scope.row)"
                >{{item}}</el-tag>
                <!-- 添加按钮 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                  style="width:200px"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column label="#" type="index"></el-table-column>
            <el-table-column label="属性名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template v-slot="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  @click="editDialog(scope.row.attr_id)"
                >编辑</el-button>
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  @click="removeParams(scope.row.attr_id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加属性对话框 -->
    <el-dialog
      :title="'添加'+titleText"
      :visible.sync="addParamsdialogVisible"
      width="50%"
      @close="addDialogClose"
    >
      <el-form :model="addForm" :rules="addFormRule" label-width="100px" ref="addparamsFormref">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addParamsdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改对话框 -->
    <el-dialog
      :title="'修改'+titleText"
      :visible.sync="editParamsdialogVisible"
      width="50%"
      @close="editDialogClose"
    >
      <el-form :model="editForm" :rules="addFormRule" label-width="100px" ref="editparamsFormref">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editParamsdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Bread from '../../base/breadcrumb'
export default {
  components: {
    bread: Bread
  },
  data() {
    return {
      editParamsdialogVisible: false,
      addParamsdialogVisible: false,
      cateList: [],
      goodsParamssProps: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
        // checkStrictly: true
      },
      goodsParamss: [],
      activeName: 'many',
      paramsmanyList: [],
      paramsonlyList: [],
      addForm: {
        attr_name: ''
      },
      addFormRule: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      },
      editForm: {}
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    async getCateList() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        return this.$message.error('获取商品分类失败')
      }
      this.cateList = res.data
      console.log(res.data)
    },
    async paramsChange() {
      this.getParamsDate()
    },
    handleTabClick() {
      console.log(this.activeName)
      this.getParamsDate()
    },
    async getParamsDate() {
      if (this.goodsParamss.length !== 3) {
        this.goodsParamss = []
        this.paramsmanyList = []
        this.paramsonlyList = []
      }
      // 根据所处面板获得参数
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        {
          params: { sel: this.activeName }
        }
      )
      console.log(res.data)
      if (res.meta.status !== 200) {
        return this.$message.error('获取参数失败')
      }
      res.data.forEach(item => {
        // eslint-disable-next-line no-unused-vars

        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        // 控制文本框显示隐藏
        item.inputVisible = false
        item.inputValue = ''
      })

      if (this.activeName === 'many') {
        this.paramsmanyList = res.data
      } else {
        this.paramsonlyList = res.data
      }
    },
    addDialogClose() {
      this.$refs.addparamsFormref.resetFields()
    },
    addParams() {
      this.$refs.addparamsFormref.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post(
          `categories/${this.cateId}/attributes`,
          {
            attr_name: this.addForm.attr_name,
            attr_sel: this.activeName
          }
        )
        if (res.meta.status !== 201) {
          return this.$message.error('添加参数失败')
        }
        this.$message.success('添加成功')
        this.addParamsdialogVisible = false
        this.getParamsDate()
      })
    },
    async editDialog(attrid) {
      this.editParamsdialogVisible = true
      const {
        data: res
      } = await this.$http.get(
        `categories/${this.cateId}/attributes/${attrid}`,
        { params: { attr_sel: this.activeName } }
      )
      if (res.meta.status !== 200) {
        return this.$message('获取编辑失败')
      }
      this.editForm = res.data
    },
    editDialogClose() {
      this.$refs.editparamsFormref.resetFields()
    },
    editParams() {
      this.$refs.editparamsFormref.validate(async valid => {
        if (!valid) return
        const {
          data: res
        } = await this.$http.put(
          `categories/${this.cateId}/attributes/${this.editForm.attr_id}`,
          { attr_name: this.editForm.attr_name, attr_sel: this.activeName }
        )
        console.log(res)
        if (res.meta.status !== 200) {
          return this.$message.error('编辑失败')
        }
        this.$message.success('编辑成功')
        this.getParamsDate()
        this.editParamsdialogVisible = false
      })
    },
    async removeParams(attrId) {
      const result = await this.$confirm(
        '此操作将永久删除该权限, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      if (result !== 'confirm') {
        return this.$message.info('已取消')
      }
      const { data: res } = await this.$http.delete(
        `categories/${this.cateId}/attributes/${attrId}`
      )
      if (res.meta.status !== 200) {
        return this.$message.error('删除失败')
      }
      this.$message.success('成功')
      this.getParamsDate()
    },
    async handleInputConfirm(input) {
      if (input.inputValue.trim().length === 0) {
        input.inputValue = ''
        input.inputVisible = false
      }
      input.attr_vals.push(input.inputValue.trim())
      input.inputValue = ''
      input.inputVisible = false

      this.setAttrVal(input)
    },
    removevals(index, input) {
      input.attr_vals.splice(index, 1)
      this.setAttrVal(input)
    },
    showInput(input) {
      input.inputVisible = true
      // 让文本框自动获得焦点
      // $nextTick 当页面元素被重新渲染后才执行回调函数中代码
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    async setAttrVal(input) {
      const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${input.attr_id}`, {
        attr_name: input.attr_name,
        attr_sel: input.attr_sel,
        attr_vals: input.attr_vals.join(' ')
      })
      if (res.meta.status !== 200) {
        return this.$message.error('修改参数失败')
      }
      this.$message.success('修改参数成功')
    }
  },
  computed: {
    // eslint-disable-next-line vue/return-in-computed-property
    titleText() {
      if (this.activeName === 'many') {
        return '动态参数'
      } else if (this.activeName === 'only') {
        return '静态属性'
      }
    },
    cateId() {
      if (this.goodsParamss.length === 3) {
        return this.goodsParamss[this.goodsParamss.length - 1]
      } else {
        return null
      }
    }
  }
}
</script>

<style lang="less" scoped>
.cat_opt {
  margin: 15px 0;
}
.el-tag {
  margin: 0 10px;
}
</style>
